package com.cskt.service.impl;

import com.cskt.domain.User;
import com.cskt.service.UserService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Collection;

/**
 * 自定义userDetailService实现
 *
 * @author admin
 * @date 2023/05/09 09:24
 **/
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(UserDetailServiceImpl.class);

    @Resource
    private UserService userService;

    /**
     * 根据用户名查询用户信息
     *
     * @param username the username identifying the user whose data is required.
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUsername(username);
        if (ObjectUtils.isEmpty(user)) {
            log.warn("用户名：{} 对应用户信息不存在", username);
            throw new UsernameNotFoundException("用户不存在");
        }
        //todo        暂时先创建一个空的权限集合，后续再完善
        Collection<? extends GrantedAuthority> authorities = new ArrayList<>();
//        获取用户信息成功，返回封装后的用户信息
        return new org.springframework.security.core.userdetails.User(
                username,
                "{bcrypt}" + user.getPassword(),
                authorities
        );
    }
}
